const router = require("koa-router")();
const qrdb = require("../../models/xmng/loginqrcode.js");
const qrcode = require("qrcode");
const wechatconfig = require("../../cfg/wechatconfig.js");
const axios = require("axios");
const base = require("../../models/Fjxx");
const jwt = require("jsonwebtoken");
const sitecfg = require("../../cfg/siteconfig.js");
const mongoose = require("mongoose");
router.prefix("/login");

router.get("/getqr", async (ctx, next) => {
  let time = new Date();
  try {
    let result = await qrdb.Save({
      expireAt: time.setTime(time.getTime() + 60 * 1000),
    });
    //正式配置
    let qrstr =
      "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
      wechatconfig.wechatauth.appid +
      "&redirect_uri=" +
      // encodeURIComponent("https://wechat.frp.mxthink.com.cn/api/login") +
      encodeURIComponent(sitecfg.qrurl)+
      "&response_type=code&scope=snsapi_base&state=" +
      result.id +
      "#wechat_redirect";
    //测试配置
    // let qrstr = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + wechatconfig.wechatauth.appid + '&redirect_uri=' + encodeURIComponent("http://www.glsglxx.cn:8800/apitest/login") + '&response_type=code&scope=snsapi_base&state=' + result.id + '#wechat_redirect'
    console.log(qrstr);
    let picurl = await qrcode.toDataURL(qrstr, {
      scale: 10,
      margin: 2,
      // color: {
      //     dark: "#010599FF",
      //     light: "#FFBF60FF"
      // }
    });

    ctx.body = { dataurl: picurl, error: false, id: result.id };
  } catch (err) {
    ctx.body = { error: true, message: err.message };
  }
});

router.get("/getwsc", async (ctx, next) => {
  ctx.body = ctx.state.socketServer;
});

router.get("/agreelogin", async (ctx, next) => {
  let wsid = ctx.query.wsid;
  let token = ctx.header.authorization;
  let wsc = ctx.state.socketClientMap.get(wsid).ws;
  wsc.send(
    JSON.stringify({
      type: "token",
      token: token,
    })
  );
  ctx.body = { error: false, message: "token传输成功!" };
});
router.get("/unagreelogin", async (ctx, next) => {
  let wsid = ctx.query.wsid;
  let token = ctx.header.authorization;
  let wsc = ctx.state.socketClientMap.get(wsid).ws;
  wsc.send(
    JSON.stringify({
      type: "cancel",
    })
  );
  ctx.body = { error: false, message: "用户取消登录" };
});
//扫码登录入口
router.get("/", async (ctx, next) => {
  let code = ctx.query.code;
  let qrid = ctx.query.state;
  let wsc = ctx.state.socketClientMap.get(qrid).ws;
  // wsc.send("scanok")
  wsc.send(
    JSON.stringify({
      type: "scanok",
    })
  );

  let tempqr = await qrdb.getByQuery({ _id: mongoose.Types.ObjectId(qrid) });
  if (!tempqr) {
    ctx.body = "登录失败，二维码过期";
    return;
  }

  let wxuserinfo = {
    code: ctx.query.code,
    openid: null,
    isbinder: false,
    error: false,
    role: null,
    accountname: "",
    classno: "",
    grade: "",
    userid: "",
    sid: "",
  };

  let getopenidurl =
    "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" +
    wechatconfig.wechatauth.appid +
    "&secret=" +
    wechatconfig.wechatauth.appsecret +
    "&code=" +
    code +
    "&grant_type=authorization_code";

  try {
    let result = await axios.get(getopenidurl);
    if (result.data.errcode) {
      ctx.body = result.data.errmsg;
      return;
    } else {
      console.log(result.data.openid);
      wxuserinfo.openid = result.data.openid;
    }
  } catch (err) {
    //获取用户授权出错了，跳转到出错页面
    console.log("获取用户授权出错:" + err);
    wxuserinfo.error = true;
    ctx.body = err;
    return;
  }

  try {
    if (!wxuserinfo.isbinder) {
      //let finduser = await nss.findbyquery({ 'wxopenid': wxuserinfo.openid })
      // let finduser = await base.myFindByQuery({ 'wxopenid': wxuserinfo.openid })
      //20211226误删除库后改进为base+baseExtendInfo双库存储
      let finduser = await base.myAggregate([
        {
          $match: {
            wxopenid: wxuserinfo.openid,
            accountType: { $in: ["教师","管理员"] },
          },
        },
        {
          $lookup: {
            from: "baseExtendInfo",
            localField: "_id",
            foreignField: "baseid",
            as: "baseExtendInfo",
          },
        },
        {
          $unwind: {
            path: "$baseExtendInfo",
            preserveNullAndEmptyArrays: true,
          },
        },
        {
          $project: {
            _id: 1,
            classno: 1,
            grade: 1,
            username: 1,
            gender: 1,
            wxopenid: 1,
            accountType: 1,
            role:1,
            "baseExtendInfo.学籍号": 1,
          },
        },
      ]);
      if (finduser.length == 1) {
        wxuserinfo.isbinder = true;
        wxuserinfo.role = finduser[0].role;
        wxuserinfo.accountType=finduser[0].accountType;
        wxuserinfo.accountname = finduser[0].username;
        wxuserinfo.userid = finduser[0]._id;
        if (
          // finduser[0].accountType == "学生" ||
          // finduser[0].accountType == "教师" 
          true
        ) {
          wxuserinfo.classno = finduser[0].classno;
          wxuserinfo.grade = finduser[0].grade;
          if (finduser[0].accountType == "学生") {
            wxuserinfo.sid = finduser[0].baseExtendInfo.学籍号;
          }
        }
      }
      let token = jwt.sign(wxuserinfo, sitecfg.tokenKey, { expiresIn: sitecfg.loginTimeOut });

      if (wxuserinfo.isbinder) {
        wsc.send(
          JSON.stringify({
            type: "authok",
          })
        );
        console.log("登录成功");
        ctx.redirect(
          sitecfg.isbindertoURL + "agreelogin?token=" + token + "&wsid=" + qrid
        );
      } else {
        wsc.send(
          JSON.stringify({
            type: "authfail",
          })
        );
        console.log("登录失败");
        encodeURI();
        ctx.redirect(
          sitecfg.isbindertoURL +
            "agreelogin?status=false&openid=" +
            wxuserinfo.openid +
            "&message=" +
            encodeURI(
              "当前微信未绑定本地帐号，确定后跳转至绑定页面，请先进行本地帐号绑定再扫码登录。"
            )
        );
      }
    }
  } catch (err) {
    //根据openid 查询数据库时出错，这里后期要放置出错界面
    wxuserinfo.error = true;
    console.log(err);
    ctx.body = err;
    return;
  }
});

module.exports = router;
